//
//  videoController.m
//  
//
//  Created by dllo on 16/1/28.
//
//

#import "videoController.h"
#import <AVFoundation/AVFoundation.h>

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface videoController ()
@property (nonatomic,assign)BOOL isplay;
@property (nonatomic,retain)UIView *playerview;
@property (nonatomic,retain)AVPlayer *player;
@property (nonatomic,retain)AVPlayerLayer *playerlayer;
@property (nonatomic,retain)AVPlayerItem *playitem;

@property (nonatomic,assign)CGFloat totalMovieDuration;

@property (nonatomic,retain)UISlider *progressSlider;

@property (nonatomic,retain)UIView *bottomView;

@property (nonatomic,retain)UIButton *playerbutton;

@property (nonatomic,retain)UILabel *timelabel;

@property (nonatomic,assign)BOOL isTap;
@end

@implementation videoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    [self creatview];
    [self addAVplayer];
    [self.player play];
    
    self.isplay = YES;
    [self addNotificationCenters];
    [self addProgressSlider];
    [self addGestureRecognizer];
    
    self.timelabel = [[UILabel  alloc]init];
    self.timelabel.text = @"00:00/00:00";
    
    [self.timelabel release];
}

-(void)dealloc{
    
    [_urlstring release];
    [_player release];
    [_playerbutton release];
    [_playerlayer release];
    [_playerview release];
    [_playitem release];
    [_bottomView release];
    [_progressSlider release];
    [super dealloc];
    
}

-(void)creatview{
    
    self.playerview = [[UIView alloc]initWithFrame:CGRectMake(0, 100, SCREEN_WIDTH, SCREEN_WIDTH * 0.618)];
    [self.view addSubview:self.playerview];
    self.playerview.backgroundColor = [UIColor orangeColor];
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_WIDTH * 0.618 -20 , SCREEN_WIDTH, 20)];
    [self.playerview addSubview:self.bottomView];
    self.bottomView.backgroundColor = [UIColor cyanColor];
    
    
    self.playerbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playerbutton.backgroundColor = [UIColor redColor];
    [self.playerbutton addTarget:self action:@selector(playerbutton) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.playerbutton];
    
    
    self.playerbutton.frame = CGRectMake(0, 0, 20, 20);
    
    [self.playerbutton setImage:[UIImage imageNamed:@"videoplayer_play"] forState:UIControlStateNormal];
    
    self.progressSlider = [[UISlider alloc]initWithFrame:CGRectMake(30, 10, SCREEN_WIDTH - 10 - 40, 5)];
    self.progressSlider.backgroundColor = [UIColor redColor];
    [self.progressSlider addTarget:self action:@selector(progressAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.progressSlider];
    
    
    
    [self.progressSlider release];
    [self.playerbutton release];
    [self.bottomView release];
    [self.playerview release];
    
    
    
    
}


//  播放页面添加轻拍手势
- (void)addGestureRecognizer {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews)];
    
    [self.view addGestureRecognizer:tap];
}
-(void)dismissAllSubViews{
    if (self.isTap == NO) {
        [UIView animateWithDuration:1.5 animations:^{
            self.bottomView.alpha = 0;
        }];
    }else{
        [UIView animateWithDuration:1.5 animations:^{
            self.bottomView.alpha = 1;
        }];
        
    }
    self.isTap = !self.isTap;
}

-(void)addAVplayer{
    
    self.urlstring = [[NSString alloc]init];
    
    self.urlstring = @"";
    

    
    self.urlstring = [self.urlstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:self.urlstring];
    
     self.playitem = [[AVPlayerItem alloc]initWithURL:url];
    self.player = [AVPlayer playerWithPlayerItem:self.playitem];
    
    self.playerlayer = [AVPlayerLayer playerLayerWithPlayer:self.player];

    
    self.playerlayer.frame = CGRectMake(10, 10,SCREEN_WIDTH - - 20, self.playerview.frame.size.height - 10);
    
   
    
    self.playerlayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    [self.playerview.layer insertSublayer:self.playerlayer atIndex:0];
    self.playerview.backgroundColor = [UIColor blackColor];
    
    [self.urlstring release];
    [self.playitem release];
    
}

-(void)addNotificationCenters{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlaydidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(statusBarOrientationchange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    
//    NSString *data;
//    NSRange range = [data rangeOfString:@"your keyword"];
//    NSMutableAttributedString *attr;
////    [attr setAttributes:@{NSForegroundColorAttributeName: yourColor
////                          range:range];
//    
    
    
}

-(void)moviePlaydidEnd:(NSNotification *)notity{
    
    NSLog(@"播放结束触发");
}
-(void)statusBarOrientationchange:(NSNotification *)notification{
    
    UIInterfaceOrientation orinetation = [[UIApplication sharedApplication]statusBarOrientation];
    if (orinetation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"向右横拼");
        [self setPlayerlayerFrame];
    }
    if (orinetation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"向左横屏");
        [self setPlayerlayerFrame];
    }
    
    if (orinetation == UIInterfaceOrientationPortrait) {
        NSLog(@"竖屏");
        [self setVerticalFrame];
    }
}

-(void)setPlayerlayerFrame{
    
    self.playerlayer.frame = CGRectMake(10, 10, SCREEN_WIDTH - 20, self.playerview.frame.size.height -10);
}

-(void)setVerticalFrame{
    
    self.playerview.frame = CGRectMake(10, 10, SCREEN_WIDTH - 20, self.playerview.frame.size.height - 10);
    
}

-(void)addProgressSlider{
    
    __block videoController *vc = self;
    
    [vc.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CGFloat duiation = CMTimeGetSeconds(self.playitem.duration);
        CGFloat current = CMTimeGetSeconds(self.player.currentTime);
        
        CGFloat rem = duiation - current;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
        
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT,totalT];
        self.timelabel.text = timeStr;
        
        //保存总时长用于手动快进和快退
        self.totalMovieDuration = duiation;
        
        
        //设置进度值 当前时间/总时长
        self.progressSlider.value = current/duiation;
    }];
    
}
-(void)progressAction{
    UISlider *slider = self.progressSlider;
    double currentTime = self.totalMovieDuration *slider.value;
    CMTime draged = CMTimeMake(currentTime, 1);
    [self.player seekToTime:draged completionHandler:^(BOOL finished) {
        [self.player play];
    }];
    
    
    
}

-(void)playButton{
    
    
//    if (self.isplay) {
//        [self.isplay pause];
//    }else{
//        [self.isplay play];
//    
//    }
//    self.isplay = !self.isplay;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
